//
//  DFStatus.swift
//  FlyBlog
//
//  Created by FEI on 16/4/13.
//  Copyright © 2016年 FEI. All rights reserved.
//

import UIKit

class DFStatus: NSObject {

    /// 微博创建时间
    var created_at: String?

    /// 微博ID
    var id:	Int64 = 0

    /// 微博信息内容
    var text: String?

    /// 微博来源
    var source: String? {
        didSet{
//            source = nil
            if let newSource = source {
                let firstRange = newSource.rangeOfString("\">")

                let secondRange = newSource.rangeOfString("</a>")

                guard let startIndex = firstRange?.endIndex else {
                    return
                }

                guard let endIndex = secondRange?.startIndex else {
                    return
                }

                source = "来自" + newSource.substringWithRange(startIndex..<endIndex)
            }
        }
    }

    /// 微博的配图 [Int], [String: AnyObject], [[String: AnyObject]]
    /// 数组,里面保存的是字典
    var pic_urls:[[String: AnyObject]]? {
        didSet {
            let count = pic_urls?.count ?? 0
            if count == 0 {
                return
            }

            storePictureURLs = [NSURL]()

            for dict in pic_urls! {
                let URLString = dict["thumbnail_pic"] as! String
                let url = NSURL(string: URLString)!

                storePictureURLs?.append(url)
            }
        }

    }

    var storePictureURLs: [NSURL]?

    var user: DFUser?

    var retweeted_status: DFStatus?

    /// 字典转模型
    init(dict: [String: AnyObject]) {
        super.init()

        setValuesForKeysWithDictionary(dict)
    }

    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            if let dict = value as? [String: AnyObject]{
            user = DFUser(dict: dict)
            }

            return
        }

        if key == "retweeted_status",let dict = value as? [String: AnyObject] {
            retweeted_status = DFStatus(dict: dict)
            return
        }
        super.setValue(value, forKey: key)
    }

    /// 字典中的key在模型中找不到对应的属性
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}

    /// 对象的打印
    override var description: String {
        get {
            let keys = ["created_at", "id", "text", "source", "pic_urls","user"]
            // 通过key在模型中招属性的值,找到属性的值,将key和值,拼接到字典里面
            return "\n \t微博模型: \(self.dictionaryWithValuesForKeys(keys).description)"
        }
    }

}
